package com.szwistar.common.comm;

import org.apache.mina.core.buffer.IoBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ModbusRtuAck extends ModbusRtuFrame implements AsyncResponse {
	protected static Logger LOG = LoggerFactory.getLogger(ModbusRtuAck.class);
	protected static Logger LOGCOMM = LoggerFactory.getLogger("comm");

	public byte bytes[];	// 数据(字节)
	public int crc;			// MODBUS-CRC16(低位字节在前，高位字节在后)

	public ModbusRtuAck(byte addr, byte func, byte[] bytes) {
		super();
		this.addr = addr;
		this.func = func;
		this.bytes = bytes;
	}

	public static ModbusRtuAck decode(IoBuffer buf) throws Exception {
		buf.mark();
		int total = buf.remaining();
		if(total < 5) { return null; }

		byte addr = buf.get();
		byte func = buf.get();
		byte len = buf.get();
		if(buf.remaining() < len+2) { buf.reset(); return null; }

		buf.position(0);
		LOGCOMM.warn("\n\t{}", buf.getHexDump());

		int crc = getCRC(buf, 0, total-2);
		int crc0 = buf.getUnsignedShort(total-2);
		if(crc != crc0) {
			throw new Exception("数据帧校验错！");
		}

		buf.position(3);
		byte bytes[] = new byte[total-5];
		buf.get(bytes);

		buf.getUnsignedShort(); // CRC
		if(buf.hasRemaining()) {
			LOG.warn("设备多发了数据：{}", buf.getHexDump());
			byte eat[] = new byte[buf.remaining()];
			buf.get(eat);
		}

		return new ModbusRtuAck(addr, func, bytes);
	}

	@Override
	public int getSequence() {
		return 0;
	}

	@Override
	public Object getSource() {
		return null;
	}

	@Override
	public Object getTarget() {
		return null;
	}

	@Override
	public void setReceiver(AsyncTranceiver receiver) {
	}

	@Override
	public AsyncTranceiver getReceiver() {
		return null;
	}
}
